package org.example.servlet;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.DAO.CommentDao;
import org.example.entity.Comment;
import org.example.entity.User;
import org.example.impl.CommentDaoImpl;
import org.example.Util.DataSourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/edit-comment")
public class EditCommentServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(EditCommentServlet.class);
    private CommentDao commentDao;

    @Override
    public void init() throws ServletException {
        this.commentDao = new CommentDaoImpl(DataSourceUtil.getDataSource());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        response.setContentType("text/html;charset=UTF-8");

        try {
            // 1. 验证用户登录状态
            if (session == null || session.getAttribute("user") == null) {
                response.sendRedirect("Userlogin.jsp?redirect=edit-comment?id=" + request.getParameter("id"));
                return;
            }

            // 2. 获取并验证评论ID
            int commentId = validateCommentId(request.getParameter("id"));
            User user = (User) session.getAttribute("user");

            // 3. 获取评论详情
            Comment comment = commentDao.getCommentById(commentId);
            if (comment == null) {
                throw new IllegalArgumentException("评论不存在");
            }

            // 4. 验证评论所有权
            if (comment.getUserId() != user.getId()) {
                throw new IllegalArgumentException("无权编辑此评论");
            }

            // 5. 设置请求属性并转发到编辑页面
            request.setAttribute("comment", comment);
            request.getRequestDispatcher("edit-comment.jsp").forward(request, response);

        } catch (IllegalArgumentException e) {
            logger.warn("参数验证失败: {}", e.getMessage());
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request, response);
        } catch (SQLException e) {
            logger.error("数据库错误: {}", e.getMessage());
            request.setAttribute("error", "获取评论失败");
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(false);

        try {
            // 1. 验证用户登录状态
            if (session == null || session.getAttribute("user") == null) {
                out.print("{\"success\":false,\"message\":\"未登录\",\"code\":401}");
                return;
            }

            // 2. 从JSON请求体中获取参数
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String jsonPayload = buffer.toString();

            if (jsonPayload.isEmpty()) {
                throw new IllegalArgumentException("请求体为空");
            }

            // 解析JSON
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonPayload);

            int commentId = jsonNode.get("commentId").asInt();
            int rating = jsonNode.get("rating").asInt();
            String content = jsonNode.get("content").asText().trim();
            User user = (User) session.getAttribute("user");

            // 3. 验证评论所有权
            if (!commentDao.isCommentOwner(commentId, user.getId())) {
                out.print("{\"success\":false,\"message\":\"无权编辑此评论\",\"code\":403}");
                return;
            }

            // 4. 更新评论
            Comment comment = new Comment();
            comment.setId(commentId);
            comment.setRating(rating);
            comment.setContent(content);

            boolean success = commentDao.updateComment(comment);

            // 5. 返回结果
            if (success) {
                out.print("{\"success\":true,\"message\":\"评论更新成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"评论更新失败\"}");
            }

        } catch (IllegalArgumentException e) {
            logger.warn("参数验证失败: {}", e.getMessage());
            out.print(String.format("{\"success\":false,\"message\":\"%s\",\"code\":400}", e.getMessage()));
        } catch (SQLException e) {
            logger.error("数据库错误: {}", e.getMessage());
            out.print("{\"success\":false,\"message\":\"数据库错误\",\"code\":500}");
        } catch (Exception e) {
            logger.error("系统错误: {}", e.getMessage());
            out.print("{\"success\":false,\"message\":\"系统错误\",\"code\":500}");
        } finally {
            out.close();
        }
    }

    private int validateCommentId(String commentIdParam) throws IllegalArgumentException {
        if (commentIdParam == null || commentIdParam.trim().isEmpty()) {
            throw new IllegalArgumentException("评论ID不能为空");
        }
        try {
            return Integer.parseInt(commentIdParam);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的评论ID格式");
        }
    }

    private int validateRating(String ratingParam) throws IllegalArgumentException {
        if (ratingParam == null || ratingParam.trim().isEmpty()) {
            throw new IllegalArgumentException("请选择评分");
        }
        try {
            int rating = Integer.parseInt(ratingParam);
            if (rating < 1 || rating > 5) {
                throw new IllegalArgumentException("评分必须在1-5之间");
            }
            return rating;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的评分格式");
        }
    }

    private String validateContent(String content) throws IllegalArgumentException {
        if (content == null || content.trim().isEmpty()) {
            throw new IllegalArgumentException("评论内容不能为空");
        }
        if (content.length() > 500) {
            throw new IllegalArgumentException("评论内容不能超过500字");
        }
        return content.trim();
    }
}